/**
 *
 */
package xlj.lib.android.base.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

public class SwitchWidget extends LinearLayout {

    /**
     * 当前选中位置
     */
    private int selectedIndex = -1;

    /**
     * 切换监听
     */
    public interface OnSwitchedListener {
        /**
         * 当前被选中的位置
         *
         * @param index int
         */
        boolean onItemSelected(int index);
    }

    /**
     * @param context Context
     */
    public SwitchWidget(Context context) {
        super(context);
    }

    /**
     * @param context Context
     * @param attrs   AttributeSet
     */
    public SwitchWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * @param context  Context
     * @param attrs    context
     * @param defStyle int
     */
    public SwitchWidget(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onFinishInflate() {
        // TODO Auto-generated method stub
        super.onFinishInflate();
        if (selectedIndex < 0) {
            setItemSelected(0);
        } else {
            setItemSelected(selectedIndex);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    ;

    /**
     * @param onSwitchedListener OnSwitchedListener
     */
    public void setOnSwitchedListener(
            final OnSwitchedListener onSwitchedListener) {
        if (onSwitchedListener == null) {
            return;
        }
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            final int index = i;
            View view = getChildAt(i);
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if(onSwitchedListener.onItemSelected(index)) {
                        setItemSelected(index);
                    }
                }
            });
            if (selectedIndex == index) {
                onSwitchedListener.onItemSelected(selectedIndex);
            }
        }
    }

    /**
     * @param index int
     */
    public void setItemSelected(int index) {
        if (index == selectedIndex) {
            return;
        }
        int count = getChildCount();
        if (selectedIndex >= 0 && selectedIndex < count) {
            View lastSelectView = getChildAt(selectedIndex);
            lastSelectView.setSelected(false);
        }
        if (index >= 0 && index < count) {
            View selectedView = getChildAt(index);
            selectedView.setSelected(true);
            selectedIndex = index;
        }
    }
}
